<template>
  <div class="app-container">

    <el-row :gutter="20">
      <div class="app-container_conter">
      <!--用户数据-->
      <!--      <el-col :span="20" :xs="24">-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" style="display: flex;justify-content: space-between;align-items: flex-end">
        <div>
        <el-form-item label="用户名称" prop="user_name">
          <el-input
              v-model="queryParams.user_name"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 200px"
          >
            <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="timeData">
          <el-date-picker
              v-model="queryParams.timeData"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        </div><div style="width: 150px">
        <el-form-item style="width: 150px;text-align: right;">
          <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="info"  size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              style="background:#0793FF ;color: #FFFFFF"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
             style="background:#0793FF ;color: #FFFFFF"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="info"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="info"

              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
          >导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="primary"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
          >导出
          </el-button>
        </el-col>
        <!--        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>-->
      </el-row>

      <el-table v-loading="loading"  :data="userList" @selection-change="handleSelectionChange"  :header-cell-style="tableHeaderColor">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="用户编号" align="center" min-width="100px" prop="user_id" />
        <el-table-column label="账号" align="center" prop="user_name" min-width="100px" :show-overflow-tooltip="true"/>
        <el-table-column label="上级用户" align="center" prop="create_by" min-width="100px"/>
        <el-table-column label="角色" align="center" prop="role_name" min-width="130px"/>
        <el-table-column label="邮箱" align="center" prop="email" min-width="150px"/>
        <el-table-column label="手机号码" align="center" prop="phonenumber"
                         min-width="120px"/>
        <el-table-column label="状态" min-width="100px" align="center"  class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180px" align="center" prop="create_time" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            min-width="160px"
        >
          <template slot-scope="scope">
            <el-button
                style="color: #0095FF"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
            >修改
            </el-button>
            <el-button
                style="color: #0095FF"
                size="mini"
                type="text"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']"
            >重置
            </el-button>
            <el-button
                style="color: #CA1414"
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
      <pagination
          style="background: transparent"
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
      <!--      </el-col>-->
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              <el-input style="width: 220px" v-model="form.userName" placeholder="请输入用户名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input style="width: 220px" v-model="form.password" placeholder="请输入用户密码" type="password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                    v-for="dict in sexOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-input readonly type="text" v-model="role_name" v-if="role_name"></el-input>
              <el-select v-else v-model="form.roleIds" multiple placeholder="请选择">
                <el-option
                    v-for="item in roleOptions"
                    :key="item.role_id"
                    :label="item.role_name"
                    :value="item.role_id"
                    :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">

          </el-col>
          <el-col :span="12">

            <el-form-item label="可看保司" prop="safetyMechanism">
              <el-select v-model="form.safetyMechanism" multiple placeholder="请选择" @change="$forceUpdate()">
                <el-option
                    v-for="(item,index) in SeeCompany"
                    :key="index"
                    :label="item.safety_mechanism"
                    :value="item.safety_mechanism"
                    @change="$forceUpdate()"
                ></el-option>
              </el-select>
              <!--              <el-select v-model="form.safetyMechanism" multiple placeholder="请选择" @change="getSafety1">-->
              <!--                <el-option-->
              <!--                    v-for="item in SeeCompany"-->
              <!--                    :key="item.safety_mechanism"-->
              <!--                    :label="item.safety_mechanism"-->
              <!--                    :value="item.safety_mechanism"-->
              <!--                ></el-option>-->
              <!--&lt;!&ndash;                 @click.native="getSafety(item)"&ndash;&gt;-->
              <!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input style="width: 220px" v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input style="width: 220px" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="备注">
              <el-input style="width: 220px" v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="info" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="650px" append-to-body>
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <img src="../../../assets/images/Import.png" style="width: 83px;height: 91px;margin: 50px 0;"/>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip" style="display: flex;justify-content: space-between;width: 600px">
          <div class="el-upload__tip" style="color:red" slot="tip">仅允许导入“xls”或“xlsx”格式文件！</div>
          <div style="display: flex;align-items: center">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px;color: #0095FF" @click="importTemplate">下载模板</el-link>
          </div>
        </div>

      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button type="info" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  exportUser,
  resetUserPwd,
  changeUserStatus,
  importTemplate,
  get_insur_list,
  add_user_after,
  get_user_detail,
  edit_user_after,
  user_list
} from "@/api/system/user";
import {getToken} from "@/utils/auth";
import {listIdCardType, get_card_type} from "@/api/base/idCardType";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Template from "../../base/template/index";
import {uploadTmage} from "@/api/base/template";

export default {
  name: "User",
  components: {Template, Treeselect},
  data() {
    return {
      url: process.env.VUE_APP_BASE_API,//地址
      //投保人签字展示显示隐藏
      show: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      timeLimit: '',
      // 日期范围
      dateRange: [],
      dateRange2: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      //证件类型
      idCardTypeOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        user_name: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        user_id: '',
        role_id: '',
        timeData: ''
      },
      queryParams1: {
        user_id: '',
        role_id: '',

      },
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户昵称`, visible: true},
        {key: 3, label: `部门`, visible: true},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `状态`, visible: true},
        {key: 6, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {

        // deptId: [
        //   {required: false, message: "请选择归属部门", trigger: 'change' }
        // ],

        userName: [
          {required: true, message: "请输入用户名称", trigger: 'blur'}
        ],
        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"}
        ],

        email: [
          {
            required: true, type: "email", message: "'请输入正确的邮箱地址", trigger: ["blur"]
          }
        ],

        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        sex: [
          {required: true, message: "请选择性别", trigger: "change"}
        ],
        // postIds:[
        //   {required: false, message: "请选择岗位", trigger: "change"}
        // ],
        roleIds: [
          {required: true, message: "请选择角色", trigger: "change"}
        ],
        safetyMechanism: [
          {required: true, message: "请选择可看保司", trigger: "change"}
        ]
        // seal:[
        //   {required: true, message: "请上传公章", trigger: "change"}
        // ]

      },
      SeeCompany: [],//可看保司
      role_name: '',//是否是当前用户
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {

    this.queryParams1.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    this.queryParams.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    var info = JSON.parse(localStorage.getItem('userInfo'));
    if (info.roles.length != 0) {
      this.queryParams1.role_id = info.roles[0].roleId
      this.queryParams.role_id = info.roles[0].roleId
    }
    this.getList();
    // this.getTreeselect();
    this.getListIdCardType();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });

  },


  methods: {
    /* 修改表头颜色 */
    tableHeaderColor({ rowIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #304156;color: #fff;font-weight: 400;font-family: Microsoft YaHei;'
      }
    },
    //查看保司
    getInsurList() {
      // console.log('queryParams1', this.queryParams1)
      get_insur_list(this.queryParams1).then(res => {
        if (res.code == 1) {
          this.SeeCompany = res.data.plan;
          this.roleOptions = res.data.role
        }
        // console.log('保司', res)
      })
    },
    getSafety1(e) {
      // this.form.safetyMechanism=e
      // console.log('e', e)
      // console.log('safetyMechanism', this.form.safetyMechanism)
    },
    getSafety(item) {
      // console.log('item', item)
    },

    /** 查询用户列表 */
    getList() {
      // console.log('queryParams', this.queryParams)

      // listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
      //     this.userList = response.rows;
      //     this.total = response.total;
      //     console.log('response12',response);
      //     this.loading = false;
      //   }
      // );
      this.loading = true;
      user_list(this.queryParams).then(res => {
        this.loading = false;
        if (res.code == 1) {
          this.userList = res.data.user;
          this.total = res.data.count;

        }
        // console.log('详情', res)
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },

    //证件类型
    getListIdCardType() {
      get_card_type().then(res => {
        this.idCardTypeOptions = res.data
        // console.log(res)
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.user_name + '"用户吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeUserStatus(row.user_id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        idCardTypeId: undefined,
        idCardNo: undefined,
        userName: undefined,
        contactName: undefined,
        nickName: undefined,
        password: undefined,
        registerAddress: undefined,
        organizationType: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],

        seal: '',//签章
        timeLimitStart: undefined,
        timeLimitEnd: undefined,
        safetyMechanism: [],

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.user_id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {

      // this.$router.push({
      //   path:'/login'
      // })
      this.reset();
      this.getInsurList();
      // this.getTreeselect();
      getUser().then(response => {

        // this.postOptions = response.posts;
        // this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
        // console.log('form', this.form);

      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // console.log('row', row)
      this.reset();
      // this.getTreeselect();
      // console.log('ids',this.ids)
      const userId = row.user_id || this.ids[0];
      // console.log('userId',userId)
      var obj = {
        user_id: this.queryParams1.user_id,
        role_id: this.queryParams1.role_id,
        sys_id:userId
      }
      // console.log('obj', obj)
      this.form.safetyMechanism = undefined;
      //  console.log('safety_mechanism23',this.form.safetyMechanism)
      get_user_detail(obj).then(res => {
        if (res.code == 1) {
          // console.log('res编辑', res)
          this.form.safetyMechanism = res.data.user.insur_company
          this.SeeCompany = res.data.insur;
          this.roleOptions = res.data.roles;
          this.role_name = res.data.user.role_name

        }
      })
      getUser(userId).then(response => {
        // console.log('respons243', response)
        this.form = response.data;
        // console.log('form', this.form)
        this.postOptions = response.posts;
        // this.roleOptions = response.roles;
        // this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;

        // console.log('roleIds', this.form.roleIds)
        if (response.data.seal != null) {
          this.urlImage = response.data.seal;
          this.show = false;
        } else {
          this.show = true;
        }
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
        // console.log('form23232', this.form);

      });

    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      console.log('row', row)
      this.$prompt('请输入"' + row.user_name + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({value}) => {
        resetUserPwd(row.user_id, value).then(response => {
          this.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      // console.log('form', this.form);
      var obj = {
        user_id: this.queryParams1.user_id,
        user_name: this.form.userName,
        insur_company: this.form.safetyMechanism,
      }
      var obj1 = {
        user_id: this.queryParams1.user_id,
        sys_id: this.form.userId,
        insur_company: this.form.safetyMechanism,
      }
      // console.log('obj', obj1);


      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              // console.log('response修改成功', response)

              this.msgSuccess("修改成功");
              this.open = false;
              // this.cancel();
              edit_user_after(obj1).then(res => {
                // console.log('修改：', res)
                this.getList();
              })
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              // this.cancel();
              // console.log('response新增成功', response)

              add_user_after(obj).then(res => {
                // console.log('res111', res)
                this.getList();
              })
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.user_id || this.ids;
      console.log('userIds', row)
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportUser(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //确认选定的值

  }
};
</script>
<style>

</style>

